<template>
  <Loading v-show="isLoading" />

  <!-- Content -->
  <div class="overflow-x-auto" v-show="!isLoading">
    <table class="table table-lg">
      <thead>
        <tr>
          <th>Name</th>
          <th>Class</th>
          <th>Subject</th>
          <th>Semester</th>
          <th>Score</th>
        </tr>
      </thead>
      <tbody>
        <ScoreListItem
          v-for="scoreItem in filteredScoreListBySearch"
          :key="scoreItem.id"
          :scoreItem
          :currentStudent="
            isStudent
              ? students[0]
              : students.find(
                  (student) => student.student_id === scoreItem.student_id
                )
          "
          v-if="students.length > 0"
        />
      </tbody>
    </table>
  </div>
</template>

<script setup>
import { onMounted, ref, computed } from 'vue';
import { storeToRefs } from 'pinia';

import { getScoreList } from '@/services/apiScore';
import { getStudentByStudentId, getStudentList } from '@/services/apiStudent';

import { getUserId } from '@/utils/userHelper';
import { useUserStore } from '@/stores/user';

import ScoreListItem from './ScoreListItem.vue';
import Loading from '@/ui/Loading.vue';
import { useSearchStore } from '@/stores/search';

const scoreList = ref([]);
const students = ref([]);

const userStore = useUserStore();
const { scoreSearchCondition } = storeToRefs(useSearchStore());

const { isStudent } = storeToRefs(userStore);

const filteredScoreList = computed(() => {
  const userId = getUserId();

  if (!isStudent.value) {
    return scoreList.value.filter((scoreItem) =>
      students.value
        .map((student) => student.student_id)
        .includes(scoreItem.student_id)
    );
  }

  return scoreList.value.filter((scoreItem) => scoreItem.student_id === userId);
});

const filteredScoreListBySearch = computed(() => {
  if (!scoreSearchCondition.value.length) {
    return filteredScoreList.value;
  }

  return filteredScoreList.value.filter((scoreItem) => {
    const scoreInfoJSON = JSON.stringify([
      scoreItem.subject.toLowerCase(),
      scoreItem.semesterYear,
      scoreItem.semesterSeason.toLowerCase(),
      scoreItem.score,
    ]);

    for (const condition of scoreSearchCondition.value) {
      if (!scoreInfoJSON.includes(condition)) {
        return false;
      }
    }

    return true;
  });
});

const isLoading = ref(true);
onMounted(async () => {
  isLoading.value = true;

  scoreList.value = await getScoreList();

  const userId = getUserId();

  if (!isStudent.value) {
    students.value = await getStudentList(userId);
  } else {
    const student = await getStudentByStudentId(userId);
    students.value = [student];
  }

  isLoading.value = false;
});
</script>
